﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Aga.GestionDeArchivos.Web.Helpers;
using Aga.GestionDeArchivos.Web.Models;
using System.Text;
using log4net.Config;
using Aga.GestionDeArchivos.Services;
using Aga.GestionDeArchivos.Domain.Entities;

namespace Aga.GestionDeArchivos.Web.Controllers
{
    public class ControllerBase : Controller
    {
        protected const int PageSize = 10;

        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            base.OnActionExecuting(filterContext);

            CheckMenu();

            ViewBag.MainMenu = new List<MenuOption>();

            if (Request.IsAuthenticated)
            {
                var user = (User)Session[SessionKey.LoggedInUser];

                ViewBag.LoggedInUser = user;

                if (user != null && !user.IsExternal)
                {
                    var helper = new MenuHelper();

                    ViewBag.MainMenu = helper.BuildMainMenu(user.Id);
                }
            }
        }

        protected override void OnAuthorization(AuthorizationContext filterContext)
        {
            base.OnAuthorization(filterContext);
        }

        /// <summary>
        /// Shows the error.
        /// </summary>
        /// <param name="ex">The ex.</param>
        /// <returns></returns>
        protected ActionResult ShowError(Exception ex)
        {
            string controllerName = this.GetType().Name.Replace("Controller", string.Empty);

            StringBuilder message = new StringBuilder(ex.Message);

            while (ex.InnerException != null)
            {
                ex = ex.InnerException;
                message.AppendFormat(" {0}", ex.Message);
            }

            ErrorViewModel model = new ErrorViewModel(controllerName)
            {
                Message = message.ToString(),
                ErrorDetails = ex.StackTrace
            };

            // Log error
            try
            {
                XmlConfigurator.Configure();
                var logger = log4net.LogManager.GetLogger("Controllers");

                logger.Error(message.ToString(), ex);
            }
            catch { }

            return View("Error", model);
        }

        protected override void OnException(ExceptionContext filterContext)
        {
            filterContext.ExceptionHandled = true;
            filterContext.Result = ShowError(filterContext.Exception);
        }

        private void CheckMenu()
        {
            try
            {
                if (ViewBag.Menu == null) // if no option
                    ViewBag.Menu = MenuKey.Home;  // default value
            }
            catch 
            {
                ViewBag.Menu = MenuKey.Home; // if error, default value
            }
            
        }
    }
}
